package server

import (
	"errors"
	"yk/common/models"
	"yk/common/proto/user"
)

func SendSms(in *user.SendRequest) (*user.SendResponse, error) {
	s := models.SendSms{
		Mobile: in.Mobile,
	}
	err := s.SendCreate()
	if err != nil {
		return nil, errors.New("服务器错误")
	}
	return &user.SendResponse{Code: s.Code}, nil
}

func Reg(in *user.RegRequest) (*user.RegResponse, error) {
	u := models.User{
		Mobile:   in.Mobile,
		Nickname: in.Nickname,
		Age:      in.Age,
		Sex:      in.Sex,
		Addr:     in.Addr,
	}
	err := u.Reg()
	if err != nil {
		return nil, errors.New("服务器错误")
	}
	return &user.RegResponse{UserId: int32(u.ID)}, nil
}

func Login(in *user.LoginRequest) (*user.LoginResponse, error) {
	login, err := models.Login(in.Mobile)
	if err != nil {
		return nil, errors.New("服务器错误")
	}
	return &user.LoginResponse{
		Mobile:   login.Mobile,
		Nickname: login.Nickname,
		Age:      login.Age,
		Sex:      login.Sex,
		Addr:     login.Addr,
	}, nil
}

func Update(in *user.UpdateRequest) (*user.UpdateResponse, error) {
	update, err := models.Update(in.UserId)
	if err != nil {
		return nil, errors.New("服务器错误")
	}
	return &user.UpdateResponse{
		Mobile:   update.Mobile,
		Nickname: update.Nickname,
		Age:      update.Age,
		Sex:      update.Sex,
		Addr:     update.Addr,
	}, nil
}

func UserXy(in *user.UserXyRequest) (*user.UserXyResponse, error) {
	u := models.UserXy{
		UserId:      in.UserId,
		CreditScore: in.CreditScore,
	}
	err := u.UserXy()
	if err != nil {
		return nil, err
	}
	return &user.UserXyResponse{YxId: int32(u.ID)}, nil
}

func OrderCarList(in *user.OrderCarListRequest) (*user.OrderCarListResponse, error) {
	list, err := models.OrderCarList()
	if err != nil {
		return nil, err
	}
	return &user.OrderCarListResponse{
		UserId:        list.UserId,
		OddNumber:     list.OddNumber,
		Distance:      list.Distance,
		Time:          list.Time,
		Price:         list.Price,
		PaymentMethod: list.PaymentMethod,
	}, nil
}

func TakeCreate(in *user.TakeCreateRequest) (*user.TakeCreateResponse, error) {
	t := models.TakeCar{
		UserId:         in.UserId,
		Origin:         in.Origin,
		Destination:    in.Destination,
		EstimatedPrice: in.EstimatedPrice,
		Price:          in.Price,
	}
	err := t.TakeCreate()
	if err != nil {
		return nil, err
	}
	return &user.TakeCreateResponse{TakeId: int32(t.ID)}, nil
}

func EvaCreate(in *user.EvaCreateRequest) (*user.EvaCreateResponse, error) {
	e := models.Evaluate{
		DriverId: in.DriverId,
		UserId:   in.UserId,
		Score:    in.Score,
		Comment:  in.Comment,
	}
	err := e.EvaCreate()
	if err != nil {
		return nil, err
	}
	return &user.EvaCreateResponse{EvaId: int32(e.ID)}, nil
}
